import { defineStore } from 'pinia'
import { login, checkPhone ,dosendCode,docheckcode,dofinishregister} from "@/api/user";
export const useCounterStore = defineStore('useCounterStore', {
  state() {
    return {
      //  储存数据
      token: localStorage.getItem("token") || '',
      userid: localStorage.getItem("userid") || '',
      loginname: localStorage.getItem("loginname") || '',
    }
  },
  actions: {
    //  写一个函数发请求登入
    async loinHandler(values: { loginname: string, password: string }) {
      //  将手机号码存入state
      this.loginname = values.loginname
      //  数据持久化
      localStorage.setItem("loginname", values.loginname)
      // 调用请求函数获取数据
      const result = await login(values)
      // 将用户id和token存起来
      // 获取成功向login页面给点反应
      if ((result as any).code == 200) {
        this.token = result.data.token
        this.userid = result.data.userid
        // 数据持久化
        localStorage.setItem("token", result.data.token)
        localStorage.setItem("userid", result.data.userid)
        return Promise.resolve("登入成功")
      } else {
        return Promise.reject("登录失败")
      }
    },
    // 校验手机号码是否被注册过
    async checkPhoneHandler(params: { tel: string }) {
      const result = await checkPhone(params)
      // 判断是否存在
      if ((result as any).code == 200) {
         // 将手机号码存储到state里面去
        this.loginname = params.tel;
        //返回一个成功的promise
        return Promise.resolve(result)
      } else {
         return Promise.reject(result)
      }
    },
    
    //获取验证码
    async getCheckCode(params:{tel:string}){
      const result = await dosendCode(params)
      if((result as any).code == 200){
        //返回一个成功的promise
        return Promise.resolve(result.data)
      }else{
        //返回又给失败的promise
        return Promise.reject(result.data)
      }
    },

    //校验验证码
    async checkCodeHandler(params:{tel:string,telcode:string}){
      const result = await docheckcode(params)
      if((result as any).code == 200){
        //返回一个成功的promise
        return Promise.resolve(result)
      }else{
        //返回又给失败的promise
        return Promise.reject(result)
      }
    },
   //校验密码
   async doRegisterHandler(params:{tel:string,password:string}){
    const result = await dofinishregister(params)
    if((result as any).code == 200){
      //返回一个成功的promise
      return Promise.resolve(result)
    }else{
      //返回又给失败的promise
      return Promise.reject(result)
    }
  },
     //退出登录
     logoutHandler(){
      this.token = ""
      this.userid = ""
      localStorage.removeItem("userid")
      localStorage.removeItem("token")
    }


  },
  getters: {

  }

})
